<template>
  <div class="permission-management">
    <div class="page-header">
      <h1 class="page-title">权限管理</h1>
      <p class="page-description">管理系统权限节点，定义权限分组和权限项</p>
    </div>

    <!-- 操作栏 -->
    <div class="action-bar">
      <div class="action-left">
        <el-button type="primary" @click="handleAddPermission">
          <el-icon>
            <Plus />
          </el-icon>
          添加权限
        </el-button>
        <el-button @click="handleRefresh">
          <el-icon>
            <Refresh />
          </el-icon>
          刷新
        </el-button>
        <el-button @click="handleExpandAll">
          <el-icon>
            <FolderOpened />
          </el-icon>
          展开全部
        </el-button>
        <el-button @click="handleCollapseAll">
          <el-icon>
            <Folder />
          </el-icon>
          收起全部
        </el-button>
      </div>
      <div class="action-right">
        <el-input v-model="searchKeyword" placeholder="搜索权限名称、代码..." :prefix-icon="Search" clearable
          style="width: 300px;" />
      </div>
    </div>

    <!-- 权限树表格 -->
    <div class="table-container">
      <el-table ref="permissionTableRef" :data="filteredTableData" style="width: 100%" v-loading="loading" row-key="id"
        stripe border :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" default-expand-all>
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="权限名称" width="200" />
        <el-table-column prop="code" label="权限代码" width="200" />
        <el-table-column prop="type" label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getPermissionTypeTag(row.type)">{{ row.type }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="200" />
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === '启用' ? 'success' : 'danger'">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleEditPermission(row)">编辑</el-button>
            <el-button size="small" type="primary" @click="handleAddChild(row)" v-if="row.type === '模块'">
              添加子权限
            </el-button>
            <el-button size="small" type="danger" @click="handleDeletePermission(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="pagination.current" v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]" :total="pagination.total" layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </div>

    <!-- 权限表单抽屉 -->
    <PermissionFormDrawer v-model:visible="drawerVisible" :permission-data="currentPermission" :is-edit="isEditMode"
      :parent-data="parentPermission" @submit="handleFormSubmit" />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh, Search, FolderOpened, Folder } from '@element-plus/icons-vue'
import PermissionFormDrawer from '@/components/AdminInfo/PermissionFormDrawer.vue'

// 响应式数据
const loading = ref(false)
const searchKeyword = ref('')
const tableData = ref([])
const pagination = ref({
  current: 1,
  pageSize: 20,
  total: 0
})

// 抽屉相关状态
const drawerVisible = ref(false)
const isEditMode = ref(false)
const currentPermission = ref({})
const parentPermission = ref({})
const permissionTableRef = ref()

// 模拟权限数据（树结构）
const mockPermissionData = [
  {
    id: 1,
    name: '用户管理',
    code: 'user',
    type: '模块',
    description: '用户相关权限',
    sort: 1,
    status: '启用',
    createTime: '2023-12-01 09:00:00',
    children: [
      {
        id: 11,
        name: '查看用户',
        code: 'user:view',
        type: '操作',
        description: '查看用户列表和详情',
        sort: 1,
        status: '启用',
        createTime: '2023-12-01 09:00:00',
        parentId: 1
      },
      {
        id: 12,
        name: '编辑用户',
        code: 'user:edit',
        type: '操作',
        description: '编辑用户信息',
        sort: 2,
        status: '启用',
        createTime: '2023-12-01 09:00:00',
        parentId: 1
      },
      {
        id: 13,
        name: '删除用户',
        code: 'user:delete',
        type: '操作',
        description: '删除用户',
        sort: 3,
        status: '启用',
        createTime: '2023-12-01 09:00:00',
        parentId: 1
      },
      {
        id: 14,
        name: '导出用户',
        code: 'user:export',
        type: '操作',
        description: '导出用户数据',
        sort: 4,
        status: '启用',
        createTime: '2023-12-01 09:00:00',
        parentId: 1
      }
    ]
  },
  {
    id: 2,
    name: '内容管理',
    code: 'content',
    type: '模块',
    description: '内容相关权限',
    sort: 2,
    status: '启用',
    createTime: '2023-12-01 09:00:00',
    children: [
      {
        id: 21,
        name: '查看内容',
        code: 'content:view',
        type: '操作',
        description: '查看内容列表和详情',
        sort: 1,
        status: '启用',
        createTime: '2023-12-01 09:00:00',
        parentId: 2
      },
      {
        id: 22,
        name: '编辑内容',
        code: 'content:edit',
        type: '操作',
        description: '编辑内容信息',
        sort: 2,
        status: '启用',
        createTime: '2023-12-01 09:00:00',
        parentId: 2
      },
      {
        id: 23,
        name: '删除内容',
        code: 'content:delete',
        type: '操作',
        description: '删除内容',
        sort: 3,
        status: '启用',
        createTime: '2023-12-01 09:00:00',
        parentId: 2
      },
      {
        id: 24,
        name: '发布内容',
        code: 'content:publish',
        type: '操作',
        description: '发布内容',
        sort: 4,
        status: '启用',
        createTime: '2023-12-01 09:00:00',
        parentId: 2
      },
      {
        id: 25,
        name: '审核内容',
        code: 'content:audit',
        type: '操作',
        description: '审核内容',
        sort: 5,
        status: '启用',
        createTime: '2023-12-01 09:00:00',
        parentId: 2
      }
    ]
  },
  {
    id: 3,
    name: '系统管理',
    code: 'system',
    type: '模块',
    description: '系统相关权限',
    sort: 3,
    status: '启用',
    createTime: '2023-12-01 09:00:00',
    children: [
      {
        id: 31,
        name: '查看系统',
        code: 'system:view',
        type: '操作',
        description: '查看系统信息',
        sort: 1,
        status: '启用',
        createTime: '2023-12-01 09:00:00',
        parentId: 3
      },
      {
        id: 32,
        name: '编辑系统',
        code: 'system:edit',
        type: '操作',
        description: '编辑系统配置',
        sort: 2,
        status: '启用',
        createTime: '2023-12-01 09:00:00',
        parentId: 3
      },
      {
        id: 33,
        name: '系统配置',
        code: 'system:config',
        type: '操作',
        description: '系统高级配置',
        sort: 3,
        status: '启用',
        createTime: '2023-12-01 09:00:00',
        parentId: 3
      }
    ]
  }
]

// 计算属性
const filteredTableData = computed(() => {
  if (!searchKeyword.value) return tableData.value

  const filterTree = (nodes) => {
    return nodes.reduce((acc, node) => {
      const matches =
        node.name.includes(searchKeyword.value) ||
        node.code.includes(searchKeyword.value) ||
        node.description.includes(searchKeyword.value)

      const filteredChildren = node.children ? filterTree(node.children) : []

      if (matches || filteredChildren.length > 0) {
        acc.push({
          ...node,
          children: filteredChildren
        })
      }

      return acc
    }, [])
  }

  return filterTree(tableData.value)
})

// 获取权限类型标签
const getPermissionTypeTag = (type) => {
  const typeMap = {
    '模块': 'primary',
    '操作': 'success',
    '页面': 'info'
  }
  return typeMap[type] || 'info'
}

// 方法
const loadData = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 800))
    tableData.value = mockPermissionData
    pagination.value.total = mockPermissionData.length
  } catch (error) {
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

const handleAddPermission = () => {
  isEditMode.value = false
  currentPermission.value = {}
  parentPermission.value = {}
  drawerVisible.value = true
}

const handleEditPermission = (row) => {
  isEditMode.value = true
  currentPermission.value = { ...row }
  parentPermission.value = {}
  drawerVisible.value = true
}

const handleAddChild = (row) => {
  isEditMode.value = false
  currentPermission.value = {}
  parentPermission.value = { ...row }
  drawerVisible.value = true
}

const handleDeletePermission = (row) => {
  ElMessageBox.confirm(
    `确定要删除权限 ${row.name} 吗？${row.children?.length ? '删除后子权限也将被删除。' : ''}`,
    '删除确认',
    {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'error',
    }
  ).then(() => {
    // 这里需要递归删除
    const deleteFromTree = (nodes, targetId) => {
      for (let i = 0; i < nodes.length; i++) {
        if (nodes[i].id === targetId) {
          nodes.splice(i, 1)
          return true
        }
        if (nodes[i].children && deleteFromTree(nodes[i].children, targetId)) {
          return true
        }
      }
      return false
    }

    deleteFromTree(tableData.value, row.id)
    ElMessage.success('删除成功')
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

const handleExpandAll = () => {
  nextTick(() => {
    permissionTableRef.value?.toggleAllSelection()
  })
}

const handleCollapseAll = () => {
  nextTick(() => {
    permissionTableRef.value?.clearSelection()
  })
}

const handleRefresh = () => {
  loadData()
}

const handleSizeChange = (val) => {
  pagination.value.pageSize = val
  loadData()
}

const handleCurrentChange = (val) => {
  pagination.value.current = val
  loadData()
}

// 处理表单提交
const handleFormSubmit = (formData) => {
  if (isEditMode.value) {
    // 编辑模式：更新现有数据
    const updateInTree = (nodes, targetId, newData) => {
      for (let node of nodes) {
        if (node.id === targetId) {
          Object.assign(node, newData)
          return true
        }
        if (node.children && updateInTree(node.children, targetId, newData)) {
          return true
        }
      }
      return false
    }

    updateInTree(tableData.value, formData.id, formData)
  } else {
    // 新增模式：添加新数据
    const newPermission = {
      ...formData,
      id: Date.now(),
      createTime: new Date().toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      }).replace(/\//g, '-')
    }

    if (parentPermission.value.id) {
      // 添加子权限
      const addToParent = (nodes, parentId, newNode) => {
        for (let node of nodes) {
          if (node.id === parentId) {
            if (!node.children) node.children = []
            node.children.push({ ...newNode, parentId })
            return true
          }
          if (node.children && addToParent(node.children, parentId, newNode)) {
            return true
          }
        }
        return false
      }

      addToParent(tableData.value, parentPermission.value.id, newPermission)
    } else {
      // 添加顶级权限
      tableData.value.unshift(newPermission)
    }

    pagination.value.total = tableData.value.length
  }
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style scoped lang="scss">
.permission-management {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.page-header {
  padding: 24px;
  border-bottom: 1px solid #f0f0f0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;

  .page-title {
    font-size: 24px;
    font-weight: 600;
    margin: 0 0 8px 0;
  }

  .page-description {
    color: rgba(255, 255, 255, 0.8);
    margin: 0;
    font-size: 14px;
  }
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background: #fafafa;
  border-bottom: 1px solid #f0f0f0;

  .action-left {
    display: flex;
    gap: 12px;
  }
}

.table-container {
  padding: 24px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;

  .el-table__header {
    background: #f8f9fa;
  }

  .el-table__row:hover {
    background: #f5f7fa;
  }
}

:deep(.el-pagination) {
  .el-pagination__total {
    color: #606266;
  }
}
</style>
